<template>
  <div class="app-container">

    <!-- 查询层 -->
     <el-card class="card" shadow="hover"  >
        <div class="card-body"  >
          <!-- 搜索区 -->
           <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">

               <el-form-item label="商品名称" prop="name">
                   <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable style="width: 240px"
                             @keyup.enter.native="handleQuery" />
               </el-form-item>


               <el-form-item>
                   <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
               </el-form-item>
           </el-form>

           </div>
    </el-card>

      <!-- 操作按钮功能层 -->
      <el-card class="card top5" shadow="never"  v-if="isMerchandiser">
        <div class="card-body"  >
           <!--功能区-->
           <el-row :gutter="10" class="mb8">
               <el-col :span="1.5">
                   <el-button
                           type="primary"
                           plain
                           icon="el-icon-plus"
                           size="mini"
                           v-if="isMerchandiser"
                           @click="handleAdd()"
                   >新增</el-button>
               </el-col>
               <el-col :span="1.5">
                   <el-button
                           type="success"
                           plain
                           icon="el-icon-edit"
                           size="mini"
                           v-if="isMerchandiser"
                           :disabled="single"
                           @click="handleUpdate()"
                   >修改</el-button>
               </el-col>
               <el-col :span="1.5">
                   <el-button
                           type="danger"
                           plain
                           icon="el-icon-delete"
                           size="mini"
                           v-if="isMerchandiser"
                           :disabled="multiple"
                           @click="handleDown()"
                   >批量下架</el-button>
               </el-col>
               <el-col :span="1.5">
                   <el-button
                           type="warning"
                           plain
                           icon="el-icon-download"
                           size="mini"
                           @click="handleExcel()"
                   >导出</el-button>
               </el-col>
           </el-row>
      </div>
    </el-card>

   <!-- 数据显示 -->
   <el-card class="card top5" shadow="never">
     <div class="card-body" >
           <!--选项卡 -->
           <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleTableClick">
               <el-tab-pane label="全部" name="all"></el-tab-pane>
               <el-tab-pane label="已上架" name="up"></el-tab-pane>
               <el-tab-pane label="未上架" name="down"></el-tab-pane>
           </el-tabs>

       <el-table :key="itemKey" :data="tableData.rows" border style="width: 100%" :default-sort = "{prop: 'id', order: 'descending'}" @sort-change="tableSort" @selection-change="handleSelectionChange">
         <el-table-column type="expand">
             <template slot-scope="scope">
               <el-form   label-width="100px">
                 <el-row style="padding: 10px;">
                   <el-col :span="24">
                     <el-form-item   label="创建时间" >
                         {{scope.row.createTime}}
                     </el-form-item>
                   </el-col>

                   <el-col :span="24">
                     <el-form-item   label="商品描述" >
                       <div v-html="scope.row.description" ></div>
                     </el-form-item>
                   </el-col>

                   <el-col :span="24" v-if="scope.row.dishFlavors">
                     <el-form-item   label="口味列表"  >
                         <div   class="flavorBox">

                           <!--商品本身有口味-->
                           <div v-if="scope.row.dishFlavors.length != 0" class="flavor">

                             <div v-for="(item ,index ) in scope.row.dishFlavors" class="cont">
                               <!--口味名称 -->
                               {{item.name}}

                               <!-- 口味明细 -->
                               <div class="labItems2">
                                <!-- <el-tag v-for="(tag,ind) in item.value" :key="tag"   :disable-transitions="false" >
                                   {{ tag }}
                                 </el-tag> -->
                                 <DivItem v-for="(tag,ind) in item.value" :key="ind"  :value="tag.value" :money="tag.price"     >

                                  </DivItem>

                               </div>

                             </div>

                           </div>
                         </div>
                     </el-form-item>
                   </el-col>

                 </el-row>
                 </el-form>
             </template>
           </el-table-column>
         <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="id" label="商品编号" width="80"  />
          <el-table-column prop="merchantName" label="商家名称"   />
          <el-table-column prop="categoryName" label="商品分类"   sortable='custom' />
          <el-table-column prop="name" label="商品名称"   />
          <el-table-column   label="商品价格"  sortable='custom' >
            <template slot-scope="scope">
               <span v-if="scope.row.price===0 && scope.row.calcPrice>0">{{scope.row.calcPrice}}[组合价]</span>
               <span v-else>{{scope.row.price}}</span>
            </template>
          </el-table-column>
          <el-table-column label="商品图片" width="220">
              <template slot-scope="scope">
                  <img :src="scope.row.picture" width="150">
              </template>
          </el-table-column>


           <el-table-column  label="库存" align="left" prop="num"   sortable='custom'>
               <template slot-scope="scope"  v-if="isMerchandiser">
                    <!-- 单个修改出现 -->
                    <div v-if="showStockEdit[scope.$index]" class="float_left">
                        <el-input v-model.number="scope.row.num" type="number" size="small" style="width:120px" placeholder="请输入内容"></el-input>
                        <el-button type="primary" size="small"    @click="changeItemStock(scope.row, scope.$index)">确定</el-button>
                        <el-button size="small" @click="showStockInput(scope.$index); "  >取消</el-button>
                    </div>
                     <label v-else>
                        <el-tag effect="dark" type="success" v-if="scope.row.num===-1">不限量</el-tag>
                        <el-tag effect="dark" v-else-if="scope.row.num>5">{{scope.row.num}} </el-tag>
                        <el-tag  effect="dark"  type="danger" v-else>{{scope.row.num}}(库存不足)</el-tag>
                        <i class="el-icon-edit" @click="showStockInput(scope.$index, scope.row.num)"></i>
                    </label>
                 </template>
                 <template  slot-scope="scope" v-else>
                   <label >
                       <el-tag effect="dark" type="success" v-if="scope.row.num===-1">不限量</el-tag>
                       <el-tag effect="dark" v-else-if="scope.row.num>5">{{scope.row.num}} </el-tag>
                       <el-tag  effect="dark"  type="danger" v-else>{{scope.row.num}}(库存不足)</el-tag>
                   </label>
                 </template>
            </el-table-column>

          <el-table-column prop="isgrounding" label="上架状态" width="155">
            <template slot-scope="scope" v-if="isMerchandiser">
               <el-switch
                   v-model="scope.row.isgrounding"
                   class="ml-2"
                   inline-prompt
                   active-text="上架"
                   inactive-text="下架"
                   active-color="#13ce66"
                   inactive-color="#ff4949"
                   active-value="1"
                   inactive-value="0"
                   @change="switchChange($event,scope.row)"

                 />
            </template>
            <template slot-scope="scope" v-else>
              <el-tag  v-for="item in dicts.product_status" :key="item.id" v-if="item.dictValue=== scope.row.isgrounding" :type="item.listClass" >{{item.dictLabel}}</el-tag>
            </template>
          </el-table-column>

         <el-table-column label="操作" align="center" v-if="isMerchandiser"  class-name="small-padding fixed-width">
             <template slot-scope="scope">
                 <el-button size="mini" type="text" icon="el-icon-edit"     @click="handleUpdate(scope.row)" >修改</el-button>
                 <el-button link type="primary" icon="icon-edit" @click="handlerCopy(scope.row)" >一键复制</el-button>
             </template>
         </el-table-column>
     </el-table>


     <!-- 分页条 -->
     <el-pagination v-if="tableData.total>0" :current-page="queryParams.page" :page-sizes="[1, 5, 10, 20,30,50,100]"
                    :page-size="queryParams.size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />

     </div>
    </el-card>

  </div>
</template>

<script>
  import {dataDictTypes } from '@/api/dictdata.js'
  import {dataApi,downBatchApi,upOrDownApi,stockChangeApi} from '@/api/product.js'
   import DivItem from '@/components/DivItem/index.vue'

  export default {
    components: {
      DivItem
    },
    computed: {
      //判断是不是商家
      isMerchandiser(){
        return this.$store.getters.accountType=== 'merchandiser'
      }
    },
    data(){
      return {
        itemKey: Math.random(),
        activeName: 'all',
        loading: false,
        // 表单查询条件对象
        queryParams:{
          page: 1,
          size: 10
        },
        // 分页表格分页的结果对象
         tableData: {
           total: 0,
           rows: []
         },
         //表格选中的对象
         mutilrows:[],
         //表格选中对象的主键的值
         ids: [],
         //编辑按钮禁用
         single: true,
         //批量下架按钮禁用
         multiple: true,
         //数据字典返回结果
         dicts: {},
          //修改库存
         showStockEdit:[],
         oldStock:[]
      }
    },
    methods:{
       //element排序字段返回对象{ column, prop, order }
       tableSort(cols){
          console.log(cols)
          this.queryParams.field = cols.prop
          if(cols.prop==='calcPrice'){
            this.queryParams.field='price'
          }else if(cols.prop==='categoryName'){
            this.queryParams.field='categoryId'
          }

          this.queryParams.order = cols.order==='ascending'? 'asc' : 'desc'
          this.handleQuery()
        },
      //点击商品状态Tabs
       handleTableClick (tab, event) {
         const value=tab.name
         if(value==='all'){
           delete   this.queryParams.isgrounding
         }else if(value==='up'){
            this.queryParams.isgrounding= 1
         }else{
            this.queryParams.isgrounding= 0
         }
          //调用分页查询方法
         this.handleQuery()
        },
      // 每页几笔发生变化
       handleSizeChange(val) {
          this.queryParams.page=1
          this.queryParams.size=val
          // 重新查询
          this.fetchData()
      },
      // 当前页发生变化
      handleCurrentChange(val) {
        this.queryParams.page=val
        // 重新查询
        this.fetchData()
      },
      // 获取后台的查询数据
      fetchData(){
        this.loading=true
        dataApi(this.queryParams).then(resp=> {
            this.tableData.total = resp.data.total
            this.tableData.rows = resp.data.list
            this.loading =false
        })
      },
      //点击搜索按钮
      handleQuery(){
        this.queryParams.page =1
        this.fetchData()
      },
      //查询数据字典的值
      fetchDictTypes() {
        const params= ['product_status']
        dataDictTypes(params).then(resp=> {
           this.dicts = resp.data
        })
      },
      handleSelectionChange(val){
       this.mutilrows = val
       //得到主键的id
       this.ids =  val.map(v=> v.id)
       //判断修改和删除属性
       this.single= val.length!==1
       this.multiple= val.length===0
      },
      //新增商品
      handleAdd(){
        this.$router.push({ path: '/product-edit' })
      },
      //修改商品
      handleUpdate(row){
        //跳转页面
         this.$router.push({ path: '/product-edit/'+row.id })
      },
      //一键复制商品
      handlerCopy(row){
        this.$router.push({ path: '/product-copy/'+row.id })
      },
      //批量下架商品
      handleDown(){
        const arr=this.mutilrows.filter(p=>p.isgrounding==='1').map(p=> p.id)
        if(arr.length===0){
           this.$message.error('选中的商品没有需要下架的');
           return;
        }

        downBatchApi(arr).then(resp=>{
            this.$message({message: '批量下架商品成功', type: 'success'});
            this.fetchData()
        })

      },
      //导出商品
      handleExcel(){

      },
      //上下架状态
      switchChange(newVal,row){
        let msg='确定要下架该商品吗?'
        if(newVal==="1"){
          msg="确定要上架该商品吗?"
        }
        this.$confirm(msg, '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                   //提交
                     const data= {
                       id: row.id,
                       merchantId: row.merchantId,
                       isgrounding: newVal
                     }
                     console.log(data)
                       //要更改
                     upOrDownApi(data).then(resp=> {
                        this.$message({message: '操作成功', type: 'success'});
                        return resolve(true)
                     }).catch(e=> {
                         return resolve(false)
                     })

                }).catch(() => {
                  //不提交操作
                    if(newVal==='0'){
                      row.isgrounding='1'
                    }else{
                       row.isgrounding='0'
                    }
                });
      },
       // 取消或编辑库存操作
       showStockInput(index, value){
          console.log(index,value)
            //取消修改
            if(value === undefined){
              this.tableData.rows[index].num =  this.oldStock[index]
              this.oldStock[index] = undefined
              this.showStockEdit[index] = false
            }else{
              // 修改价格
              this.showStockEdit[index] = true
              this.oldStock[index] = value
            }
            //更改key,使用表格重绘
             this.itemKey = Math.random()
         },

         // 修改库存保存操作
          changeItemStock(row, index) {
             console.log(index,row)
           if (row.num) {
               const stock= parseInt(row.num);
               if(stock<-1){
                  this.$message.error('商品库存不能小于-1');
                  return;
               }

               let data = {
                   id: row.id,
                   merchantId: row.merchantId,
                   num: stock
               }
               stockChangeApi(data).then(res => {
                  this.$message({message: '库存更改成功', type: 'success'});
                  this.oldStock[index]=stock
                   //取消编辑样式
                   showStockInput(index);
               }).catch(err => {
                 //取消编辑样式
                 showStockInput(index);
               });
               //更改key,使用表格重绘
                this.itemKey = Math.random()
           } else {
              this.$message.error('商品库存不能为空');
           }
      }
    },
    created() {
      this.fetchData()
      //更改key,使用表格重绘
       this.itemKey = Math.random()
    }
  }
</script>

<style scoped>
  .top5{
    margin-top: 5px;
  }

  .btn-danger{
    color: #f56c6c;
  }
</style>
